package com.nullpointer.xchatfinal.fragment;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

import com.nullpointer.xchatfinal.MainActivity;
import com.nullpointer.xchatfinal.R;
import com.nullpointer.xchatfinal.adapter.UserAdapter;
import com.nullpointer.xchatfinal.object.User;
import com.nullpointer.xchatfinal.service.ChatService;
import com.nullpointer.xchatfinal.utils.DataManager;
import com.nullpointer.xchatfinal.utils.KiraGameLog;
import com.nullpointer.xchatfinal.utils.Utils;
import com.quickblox.core.Consts;
import com.quickblox.core.QBEntityCallbackImpl;
import com.quickblox.core.request.QBPagedRequestBuilder;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;

public class SuggestedFriendsFragment extends Fragment {

	private ListView lvUsers;
	private List<User> userData = new ArrayList<User>();
	private UserAdapter userAdapter;
	private Set<Integer> currentUserIDsInList = new HashSet<>();
	private int currentPageRequest = 1;
	private int page = 1;
	private boolean isLoadDone = true;
	private boolean canLoadMore = false;
	private final int SIZE_PER_PAGE = 50;
	private View footerView;

	public static SuggestedFriendsFragment newInstance() {
		SuggestedFriendsFragment f = new SuggestedFriendsFragment();
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_suggested_friends,
				container, false);
		footerView = inflater.inflate(R.layout.view_item_load_more, null);
		findViewIds(view);
		init();
		setEvent();
		return view;
	}

	private void init() {
		lvUsers.addFooterView(footerView);
		footerView.setVisibility(View.GONE);
		userAdapter = new UserAdapter(getActivity(), userData);
		lvUsers.setAdapter(userAdapter);
		refreshData();
	}

	public void refreshData() {
		isLoadDone = true;
		canLoadMore = false;
		currentPageRequest = 1;
		page = 1;
		clearUserData();
		showLoadingInfo();
		getSuggestedUserOnline(currentPageRequest);
	}

	private void setEvent() {
		lvUsers.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (view.getLastVisiblePosition() >= totalItemCount - 1) {
					if (!canLoadMore) {
						return;
					}
					moreLoad();
				}
			}
		});
	}

	private void findViewIds(View view) {
		lvUsers = (ListView) view.findViewById(R.id.lv_users);
	}

	private void clearUserData() {
		userData.clear();
		currentUserIDsInList.clear();
		userAdapter.notifyDataSetChanged();
	}

	public void moreLoad() {
		if (!isLoadDone) {
			return;
		}
		KiraGameLog.d("load more with page " + page);
		isLoadDone = false;
		page++;
		showLoadMoreView();
		getSuggestedUserOnline(currentPageRequest + 1);
	}

	private void getSuggestedUserOnline(int pageRequest) {
		showLoadingAnimation();
		ArrayList<String> userTags = new ArrayList<String>();
		userTags.add(ChatService.ONLINE);
		userTags.add(ChatService.VISIBLE);
		// userTags.add(ChatService.USER);
		QBPagedRequestBuilder pagedRequestBuilder = new QBPagedRequestBuilder();
		pagedRequestBuilder.setPage(pageRequest);
		pagedRequestBuilder.setPerPage(SIZE_PER_PAGE);
		QBUsers.getUsersByTags(userTags, pagedRequestBuilder,
				new QBEntityCallbackImpl<ArrayList<QBUser>>() {
					@Override
					public void onSuccess(ArrayList<QBUser> users, Bundle params) {
						if (users == null || users.size() == 0) {
							isLoadDone = true;
							canLoadMore = false;
							hideLoadingAnimation();
						} else {
							// Collections.shuffle(users);
							for (QBUser user : users) {
								if (isValidSuggestedUser(user)) {
									currentUserIDsInList.add(user.getId());
									userData.add(Utils
											.convertQBUserToUser(user));
								}

							}
							userAdapter.notifyDataSetChanged();
							int totalEntries = params
									.getInt(Consts.TOTAL_ENTRIES);
							currentPageRequest = params
									.getInt(Consts.CURR_PAGE);
							int perPage = params.getInt(Consts.PER_PAGE);
							int totalPage = (totalEntries / perPage) + 1;

							KiraGameLog.d("totalEntries: " + totalEntries
									+ " currentPageRequest "
									+ currentPageRequest + " totalPage "
									+ totalPage + " data size "
									+ userData.size());

							if (userData.size() < (SIZE_PER_PAGE * page)
									&& currentPageRequest < totalPage) {
								getSuggestedUserOnline(currentPageRequest + 1);
							} else {
								// load done
								hideLoadingAnimation();
								isLoadDone = true;
								if (currentPageRequest < totalPage) {
									canLoadMore = true;
								} else {
									canLoadMore = false;
								}
								// if (!DataManager.getInstance(getActivity())
								// .isShowPost()) {
								// showSayHi();
								// DataManager.getInstance(getActivity())
								// .setIsShowPost(true);
								// }
							}
						}
					}

					@Override
					public void onError(List<String> errors) {
						KiraGameLog.d("getSuggestedUserOnline error " + errors);
						hideLoadingAnimation();
						isLoadDone = true;
						canLoadMore = false;
						// if (!DataManager.getInstance(MainActivity.this)
						// .isShowPost()) {
						// showSayHi();
						// DataManager.getInstance(MainActivity.this)
						// .setIsShowPost(true);
						// }
					}
				});
	}

	public boolean isValidSuggestedUser(QBUser user) {
		if (!Utils.isOnline(user)) {
			return false;
		}

		if (DataManager.getInstance(getActivity()).getBlockUsers()
				.contains(Integer.toString(user.getId()))) {
			return false;
		}
		if (currentUserIDsInList.contains(user.getId())) {
			return false;
		}
		return true;
	}

	private void showLoadingInfo() {
		try {
			((MainActivity) getActivity()).showInfo("loading data...", true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showLoadMoreView() {
		footerView.setVisibility(View.VISIBLE);
	}

	public void showLoadingAnimation() {
		try {
			((MainActivity) getActivity()).startRefeshAnimation();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void hideLoadingAnimation() {
		try {
			((MainActivity) getActivity()).stopRefeshAnimation();
			((MainActivity) getActivity()).hideInfo();
		} catch (Exception e) {
			e.printStackTrace();
		}
		footerView.setVisibility(View.GONE);
	}

}
